<?php
class FdhtSession implements ISession {
	private $session_options;
	
	public function __construct($session_options = array()) {
		$this->session_options = array_merge ( array ('session_name' => preg_replace ( '/[^\w]/', '_', strtoupper ( WEBSITE ) . '_SID' ), 'session_expire' => 900 ), $session_options );
		$this->start_session ();
	}
	/**
	 * 设置SESSION,当$value=null时从SESSION中删除$name.
	 * @param string $name
	 * @param mixed $value	 
	 */
	public function add($name, $value = null) {
		if (is_null ( $value )) {
			unset ( $_SESSION [$name] );
		} else {
			$_SESSION [$name] = $value;
		}
	}
	/**
	 * 从SESSION读取数据
	 * @param string $name
	 * @param mixed $default
	 * @return mixed
	 */
	public function get($name, $default = "") {
		if (isset ( $_SESSION [$name] )) {
			return $_SESSION [$name];
		} else {
			return $default;
		}
	}
	//开启会话
	private function start_session() {
		global $__sid;
		if (empty ( $__sid )) {
			@ini_set ( 'session.use_cookies', 1 );
			extract ( $this->session_options );
			
			$__sid = isset ( $_COOKIE [$session_name] ) ? $_COOKIE [$session_name] : null;
			if (! empty ( $__sid )) {
				$this->start_session_step2 ( $session_name, $session_expire );
				session_id ( $__sid );
				@session_start ();
			} else {
				$this->start_session_step2 ( $session_name, $session_expire );
				@session_start ();
				$__sid = session_id ();
			}
		}
	}
	//第二步
	private function start_session_step2($name, $expire) {
		global $__fdht_expire;
		if (! is_numeric ( $expire )) {
			$__fdht_expire = 900;
		} else {
			$__fdht_expire = $expire;
		}
		@session_set_cookie_params ( $__fdht_expire );
		@session_cache_expire ( $__fdht_expire );
		@session_name ( $name );
	}
}
//open
function __fdht_sess_open($save_path, $session_name) {
	return true;
}
//close
function __fdht_sess_close() {
	return true;
}
//read session data from fastdht
function __fdht_sess_read($id) {
	global $__fdht_expire;
	$rst = fastdht_get ( 'nutzp', 'sess', $id, false, $__fdht_expire );
	return $rst;
}
//save session data to fastdht
function __fdht_sess_write($id, $sess_data) {
	global $__fdht_expire;
	$rst = fastdht_set ( 'nutzp', 'sess', $id, $sess_data, $__fdht_expire );
	return $rst === 0;
}
//destory
function __fdht_sess_destroy($id) {
	fastdht_delete ( "nutzp", "sess", $id );
	return true;
}
//gc for fdht session
function __fdht_sess_gc($maxlifetime) {
	return true;
}
if (function_exists ( "fastdht_set" )) {
	session_set_save_handler ( "__fdht_sess_open", "__fdht_sess_close", "__fdht_sess_read", "__fdht_sess_write", "__fdht_sess_destroy", "__fdht_sess_gc" );
}
//end of file